package com.example.demo05.config;


import com.example.demo05.securityHandler.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;


@Configuration
//适配器
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    //未登录
    @Autowired
    private CustomizeAuthenticationEntryPoint customizeAuthenticationEntryPoint;
   //成功
    @Autowired
    private CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
    //失败
    @Autowired
    private CustomizeAuthenticationFailureHandler customizeAuthenticationFailureHandler;

    //异常
    @Autowired
    private CustomizeSessionInformationExpiredStarategy customizeSessionInformationExpiredStarategy;


    @Autowired
    private CustomizeLogoutHandler customizeLogoutHandler;

    //登出成功
    @Autowired
    private CustomizeLogoutSuccessHandler customizeLogoutSuccessHandler;


    //锁定
    @Autowired
    private CustomizeAccessDeniedHandler customizeAccessDeniedHandler;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
    //强hash方式加密
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request（cors 预检请求）
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();

        http.cors();

        http.authorizeRequests()
                .antMatchers("/login","/user/check").permitAll()//放行
                .anyRequest()//任何请求
                .authenticated()//都需要身份认证
                .and()
                .formLogin()
                //.loginPage("/login.html")//指定登陆页面所在的url
                //.loginProcessingUrl("/login")//指定让UsernamePasswordAuthenticationFilter拦截器拦截的路径
                .successHandler(customizeAuthenticationSuccessHandler) //登录成功处理逻辑
                .failureHandler(customizeAuthenticationFailureHandler) //登录失败处理逻辑
                .and().logout()
                .permitAll() //允许所有用户
                .addLogoutHandler(customizeLogoutHandler)
                .logoutSuccessHandler(customizeLogoutSuccessHandler) //登出成功处理逻辑
                .deleteCookies("JSESSIONID")
                .and().exceptionHandling()
                .authenticationEntryPoint(customizeAuthenticationEntryPoint)//异常处理逻辑
                .accessDeniedHandler(customizeAccessDeniedHandler) //权限不足处理逻辑
               //.and().addFilter(new LoginFilter(authenticationManager()))
                .and().sessionManagement()
                .maximumSessions(1) //同一账号同时登录最大用户数
                .expiredSessionStrategy(customizeSessionInformationExpiredStarategy);
                //.defaultSuccessUrl("/home.html")//默认登录成功后跳转的页面
                http.csrf().disable();//跨站请求伪造防护功能 disable掉
                http.headers().frameOptions().sameOrigin();
//               http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
//        UsernamePasswordAuthenticationFilter authenticationFilter =
//                new JsonAuthenticationFilter();
//        authenticationFilter.setAuthenticationManager(authenticationManagerBean());
//        http.addFilterAt(authenticationFilter,UsernamePasswordAuthenticationFilter.class);
    }

   @Bean
   CorsConfigurationSource corsConfigurationSource(){
       CorsConfiguration configuration = new CorsConfiguration();
       // 如果所有的属性不全部配置，一定要执行该方法
       configuration.applyPermitDefaultValues();

       configuration.addAllowedOriginPattern("*");
       configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
       configuration.addAllowedHeader("*");
       configuration.setAllowCredentials(true);
       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
       source.registerCorsConfiguration("/**",configuration);
       return source;
   }

//   @Bean
//    CustomAuthenticationFilter customAuthenticationFilter() throws Exception{
//        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
//        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
//            @Override
//            public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//                //返回json数据
//                JsonResult result = ResultTool.success();
//                log.info("set登陆成功");
//                TurnJson.JsonWrite(httpServletResponse,result);
//            }
//        });
//
//
//        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
//            @Override
//            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
//               JsonResult result = ResultTool.fail();
//               log.info("set登录失败");
//               TurnJson.JsonWrite(httpServletResponse,result);
//            }
//        });
//        filter.setAuthenticationManager(authenticationManagerBean());
//        return filter;
//   }







//   @Bean
//   public UserDetailsService userDetailsService() {
//      //根据用户名查找用户信息
//
//
//       return username -> {
//          Users users = userService.getbyid(username);
//          if (users == null) {
//              throw new UsernameNotFoundException("用户名未找到");
//          }
//
//          String password = users.getPassword();
//          PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
//          String passwordAfterEncoder = passwordEncoder.encode(password);//encode()加密
//           log.info("加密后数据库密码{}",passwordAfterEncoder);
//           //mathches security调用   比较 输入密码 和 数据库密码
//          return User.withUsername(username).password(passwordAfterEncoder).roles("").build();
//      };
//  }


}
